package model

import (
	"chat-room/server/global"
	"database/sql"
	"errors"
	"fmt"
)

//user结构体
type User struct {
	Id int `json:"id"`
	Name string `json:"name"`
	Account string `json:"account"`
	Password string `json:"password"`
}

//根据账号查询用户信息
func (that *User) GetUserInfoByAccount (account string) (err error) {
	stmt, err := global.MysqlDb.Prepare("select `id`,`name`,`account`,`password` from `user` where `account` = ?")
	if err != nil {
		errStr := fmt.Sprintf("预编译sql错误：%v",err)
		err = errors.New(errStr)
		return
	}

	defer func() {
		_ = stmt.Close()
	}()

	row := stmt.QueryRow(account)
	err = row.Scan(&that.Id,&that.Name,&that.Account,&that.Password);
	if err != nil {
		if err == sql.ErrNoRows {
			return nil
		}
		errStr := fmt.Sprintf("赋值错误：%v",err)
		err = errors.New(errStr)
		return
	}
	return
}

//添加用户
func (that *User) AddUser(name string, account string, password string) (err error){
	stmt, err := global.MysqlDb.Prepare("insert into `user` (`name`, `account`, `password`) values (?, ?, ?)")
	if err != nil {
		errStr := fmt.Sprintf("预编译sql错误：%v",err)
		err = errors.New(errStr)
		return
	}

	defer func() {
		_ = stmt.Close()
	}()

	_, err = stmt.Exec(name, account, password)
	if err != nil {
		errStr := fmt.Sprintf("添加数据错误：%v",err)
		err = errors.New(errStr)
		return
	}
	return 
}
